class ProjectsController < ApplicationController
  include SimpleCaptcha::ControllerHelpers

  before_action :authenticate_user!, except: [:index, :show, :team, :invest, :messages]
  # before_action :authenticate_user!
  # before_action do
  #   raise CanCan::AccessDenied unless current_user.has_role?(:admin)
  # end

  def new
    authorize! :create, Project
    @project = Project.new
  end

  def edit
    @project = Project.find(params[:id])
    authorize! :update, @project
  end

  # 创建第一步
  def create
    authorize! :create, Project
    @project = Project.new( project_params )

    if params[:industries].blank?
      @project.errors.add(:industries, '必须选择一个分类')
      render_fail('创建失败', @project)
      return
    else
      params[:industries].to_a.each do |industry|
        category = Category.find(industry[:id])
        @project.categories << category
      end
    end
    
    if params[:city].blank?
      @project.errors.add(:city, '必须选择一个城市')
      render_fail('创建失败', @project)
      return
    else
      city = City.find_or_create_by(name: params[:city])
      @project.cities << city
    end

    if params[:logo_id].present?
      @project.logo = Logo.find( params[:logo_id] )
    else
      render_fail('创建失败', logo_error: '必须上传 Logo') 
      return
    end

    if params[:screenshot_id].present?
      @project.screenshots << Screenshot.find( params[:screenshot_id] )
    else
      render_fail('创建失败', screenshot_error: '必须上传截图') 
      return
    end

    @project.add_owner( current_user )
    if @project.save
      render_success(nil, id: @project.id)
    else
      render_fail('创建失败', @project)
    end
  end

  def dirty_update
    @project = Project.find( params[:id] )
    authorize! :update, @project
    if @project.update(description: params[:description])
      render_success
    else
      render_fail
    end
  end

  def screenshots_update
    @project = Project.find( params[:id] )
    authorize! :update, @project
    @project.screenshots = params[:ids].to_a.map do |id|
      Screenshot.find(id)
    end
    if @project.save(validate: false)
      render_success
    else
      render_fail
    end
  end

  def update
    @project = Project.find( params[:id] )
    authorize! :update, @project

    if params[:logo_id]
      logo = Logo.find( params[:logo_id] )
      @project.logo = logo
    end

    if params[:industries].blank?
      @project.errors.add(:industries, '至少要选择一个分类')
      render_fail('创建失败', @project)
      return
    else
      @project.categories.delete_all
      params[:industries].to_a.each do |industry|
        category = Category.find(industry[:id])
        @project.categories << category
      end
    end

    if params[:city].blank?
      @project.errors.add(:city, '必须选择一个城市')
      render_fail('创建失败', @project)
      return
    else
      @project.cities.delete_all
      city = City.find_or_create_by(name: params[:city])
      @project.cities << city
    end

    if params[:screenshot_id].present?
      @project.screenshots << Screenshot.find( params[:screenshot_id] )
    else
      render_fail('创建失败', screenshot_error: '必须上传截图') 
      return
    end

    if @project.update( project_params )
      render_success
    else
      render_fail('更新失败', @project)
    end
  end

  def show
    @project = Project.find(params[:id])
    @calendars = ProjectCalendar.where( :project_id => params[:id] )
    @plans = ProjectPlan.where( :project_id => params[:id] ).first
    respond_to do |format|
      format.json { render partial: "project" }
      format.html
    end
  end

  def messages
    @project_message = ProjectMessage.where(project_id: params[:id],reply_id: [0,nil],isshow: true).limit(8)
    respond_to do |format|
      format.json
      format.html
    end
  end

  def uptalk
    @project = Project.find(params[:id])
    if(!@project)
      render_fail('项目未找到！')
    end
    p params
    if(params[:messages]=='')
      render_fail('内容不能为空！')
    end
    if simple_captcha_valid?
      @project_message = ProjectMessage.new
      @project_message.user_id = current_user.id
      @project_message.project_id = params[:id]
      @project_message.reply_id = 0
      @project_message.message = params[:messages]
      @project_message.isshow = false
      @project_message.save()
      render_success('留言发布成功，请等待管理员审核！')
    else
      render_fail('验证码错误！')
    end
  end

  def team
    @project = Project.find( params[:id] )
    @owner = @project.owner
    @owner_member = @project.member( @owner )
    @members = @project.members_but( @owner )
  end

  def invest
    @project = Project.find( params[:id] )
    @star_users = @project.star_users
    @money_require = @project.opened_money_require
  end

  def plan_save
    @project = Project.find(params[:project_id])
    if(!@project)
      render_fail('项目未找到！')
    end
    @plans = ProjectPlan.where( :project_id => params[:project_id] ).first
    if @plans.blank?
      @plans = ProjectPlan.new
      @plans.project_id = params[:project_id]
    end
    if simple_captcha_valid?
      @plans.message = params[:messages]
      @plans.save()
      render_success('项目运营信息发布成功！')
    else
      render_fail('验证码错误！')
    end
  end

  def calendar_save
    @project = Project.find(params[:project_id])
    if(!@project)
      render_fail('项目未找到！')
    end
    if(params[:messages]=='')
      render_fail('内容不能为空！')
    end
    if simple_captcha_valid?
      @projectCalendar = ProjectCalendar.new
      @projectCalendar.project_id = params[:project_id]
      @projectCalendar.message = params[:messages]
      @projectCalendar.dodate = params[:update].to_datetime.strftime('%Y-%m-%d')
      @projectCalendar.save()
      render_success('项目运营信息发布成功！')
    else
      render_fail('验证码错误！')
    end
  end

  def doc_save
    @project = Project.find(params[:project_id])
    if(!@project)
      render_fail('项目未找到！')
    end
    @plans = ProjectPlan.where( :project_id => params[:project_id] ).first
    if @plans.blank?
      @plans = ProjectPlan.new
      @plans.project_id = params[:project_id]
    end
    if params[:file]
      @plans.plan = params[:file]
    end
    if @plans.save
      render_success('')
    else
      render_fail( valid_on(@plans, :plan) )
    end
  end

  def plan_edit
    @plans = ProjectPlan.where( :project_id => params[:project_id] ).first
    if @plans.blank?
      @plans = ProjectPlan.new
    end
    @project = Project.find( params[:project_id] )
  end

  def calendar_edit
    if params[:project_calendar_id].present? and params[:project_calendar_id] > 0
      @project_calendar = ProjectCalendar.find(params[:project_calendar_id])
    else
      @project_calendar = ProjectCalendar.new
    end
    @calendars = ProjectCalendar.where( :project_id => params[:project_id] )
    @project = Project.find( params[:project_id] )
  end

  def calendar_del
    @calendar = ProjectCalendar.find(params[:calendar_id])
    if !@calendar.blank?
      @calendar.update_attributes(:deleted_at => Time.now.utc)
    end
    render_success("[项目运营信息删除成功]")
    return
  end

  def plan_del
  end

  private
  def project_params
    params.permit(:name, :oneword, :link, :description)
  end

  def logo_params
    params.permit(:logo_id)
  end

end
